#include "StdAfx.h"
#include "ConnectSocket.h"

CConnectSocket::CConnectSocket(void)
{
	connectSocket = INVALID_SOCKET;
}

CConnectSocket::~CConnectSocket(void)
{
	shutdown(connectSocket, SD_BOTH);	//giai phong cai tai nguyen su dung cho viec nhan, gui data
	closesocket(connectSocket);			//dong socket
}

bool CConnectSocket::Connect(const char *szServerAddr, const char *szServerPort) {
	struct addrinfo		*result = NULL;
    struct addrinfo		hints;
	int iResult;

	ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
	
	iResult = getaddrinfo(szServerAddr, szServerPort, &hints, &result);
	if (iResult != 0) 
        return 0;

	for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        connectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        if (connectSocket == INVALID_SOCKET) 
            return 0;

        // Connect to server.
        iResult = connect(connectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            closesocket(connectSocket);
            connectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);
	if (connectSocket == INVALID_SOCKET)
		return 0;
	return 1;
}

int CConnectSocket::Receive(void *lpBuffer, int nBufLen, int nFlag) {
	return recv(connectSocket, (char*)lpBuffer, nBufLen, nFlag);
}

int CConnectSocket::Send(const void *lpBuffer, int nBufLen, int nFlag) {
	return send(connectSocket, (const char*)lpBuffer, nBufLen, nFlag);
}

void CConnectSocket::Close() {
	shutdown(connectSocket, SD_BOTH);
	closesocket(connectSocket);
	connectSocket = INVALID_SOCKET;
}

void CConnectSocket::Create(const SOCKET *pSock) {
	connectSocket = *pSock;
}

SOCKET& CConnectSocket::GetSocket() {
	return connectSocket;
}
